package br.com.social.mobile.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.social.mobile.dao.ActivationDAO;
import br.com.social.mobile.dao.ParameterDAO;
import br.com.social.mobile.entities.Activation;
import br.com.social.mobile.handler.ProfileHandler;

public class RegisterServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		try { 
			String key = request.getParameter("key");
			
			ParameterDAO parameterDAO = new ParameterDAO();
			parameterDAO.forceOpenConnection();			
			
			if (!key.equals("fast")) {
				HttpSession session = request.getSession();
	
				ProfileHandler profileHandler = new ProfileHandler();
				if (profileHandler.checkKeyRegister(key)) {
					session.setAttribute("KEY_REGISTER", key);
					
					response.sendRedirect("register.html");
				} else {
					response.sendRedirect("invalid_key.html");	
				}
			} else {
				Activation activation = new Activation();
				activation.setDsKey(String.valueOf(new Date().getTime()));
				activation.setNuIdProfile(1l);
				activation.setIsUsed("N");
				
				ActivationDAO activationDAO = new ActivationDAO();
				activationDAO.save(activation);
				
				
				response.setContentType("text/html");
				PrintWriter writer = response.getWriter();
				writer.print("http://sswbr.com/social-mobile-web/register?key=" + activation.getDsKey());
				writer.flush();
				writer.close();

			}
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}   	       
	}

	
}